/**
 * 
 */
package org.ccay.excel.importer.service.impl.internal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ccay.core.exception.ExceptionHandler;
import org.ccay.core.exception.impl.ExceptionMessageManager;
import org.ccay.excel.exception.ExcelApplicationException;
import org.ccay.excel.importer.AbstractExcelDataProcessor;
import org.ccay.excel.importer.ExcelCellError;
import org.ccay.excel.importer.ExcelImportConstants;
import org.ccay.excel.importer.IExcelImportContext;
import org.ccay.excel.importer.RowData;

/**
 * VO转换处理
 * 
 * @author chaowangbang
 *
 */
public class VOConvertProcessor extends AbstractExcelDataProcessor {
	
	private IVOConverter voConverter;
	
	/**
	 * @param voClass
	 */
	public VOConvertProcessor(Class<?> voClass) {
		// TODO：可以使用工厂模式获取合适的VO转换器
		this.voConverter = new VOConverterByOgnl(voClass);
	}

	/* (non-Javadoc)
	 * @see org.ccay.excel.importer.service.impl.internal.IExcelDataProcessor#process(org.ccay.excel.importer.service.impl.internal.ExcelParseContext)
	 */
	public List<?> process(List<?> datas, IExcelImportContext context)
			throws ExcelApplicationException {
		if(datas==null || datas.isEmpty()) {
			return null;
		}
		
		List<Object> vos = new ArrayList<Object>(datas.size());
		String sheetName = context.getCurrentSheet().getPartSheetName();
		String excelSheetName = context.getNameDisplayNameMap().get(sheetName);
		for(int i=0; i<datas.size(); i++) {
			RowData rd = (RowData)datas.get(i);
			Map<String, Object> properties = populateVOProperties(rd, context);
			try {
				Object vo = voConverter.convert(properties);
				vos.add(vo);
			} catch (ConvertException e) {
				ExceptionHandler.logException(e);
				ExcelCellError error = new ExcelCellError(
						excelSheetName, // sheet的名称
						rd.rowIndex, // 行索引 
						"", // 列索引
						ExceptionMessageManager.getMessage(ExcelImportConstants.VO_MAPPING_EXCEPTION)); // 消息
				context.addCellError(error);  //添加错误信息
				//throw new ExcelImportException(ExcelImportConstants.VO_MAPPING_EXCEPTION, e);
			}
		}
		return vos;
	}
	
	/**
	 * 将行数据转换成属性-->值的映射关系表。
	 * 
	 * @param rd
	 * @param context
	 * @return
	 */
	private Map<String, Object> populateVOProperties(RowData rd, IExcelImportContext context) {
		Map<String, Object> properties = new HashMap<String, Object>();
		properties.put("rowIdx", rd.rowIndex);
		for(int j =0; j<rd.colsIndex.length; j++) {
			String col = rd.colsIndex[j];
			Object data = rd.colsData[j];
			if("".equals(data)){
				data = null;
			}
			
			col = context.getTitleMapper().getFieldByColIndex(col);
			properties.put(col, data);
		}
		return properties;
	}

}
